from flask import Flask
from redis import StrictRedis
from flask_wtf.csrf import CSRFProtect
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy

from application.settings.dev import DevelopementConfig
from application.settings.prop import ProductionConfig

# from application.models import *

config = {
    "dev": DevelopementConfig,
    "prop": ProductionConfig,
}

# 为了方便redis的连接对象在函数外部可以使用,预先设置一个全局变量,接下来在函数中用于保存redis的连接
redis_store = None

db = SQLAlchemy()


def init_app(config_name):
    """项目的初始化功能"""
    app = Flask(__name__)

    # 设置配置类
    Config = config[config_name]
    # 加载配置
    app.config.from_object(Config)

    # redis的链接初始化
    global redis_store
    redis_store = StrictRedis(host=Config.REDIS_HOST,
                              port=Config.REDIS_PORT, db=0)

    # 开启CSRF防范功能
    CSRFProtect(app)

    # 开启session功能
    # Session(app)

    # 配置数据库链接
    db.init_app(app)

    # TODO 注册蓝图对象到app应用中
    # 用户模块
    from .users import users
    app.register_blueprint(users, url_prefix='/users')

    return app
